package com.rocky.study.serial;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

public class SerialPrintDemo2 {

    static AtomicInteger NUM = new AtomicInteger(100);

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);
        for (int i = 0; i <= 100; i++) {
            int finalI = i;
            new Thread(() -> {
                boolean isAcquired = false;
                try {
                    semaphore.acquire();
                    isAcquired = true;
                    System.out.println(Thread.currentThread().getName() + "处理:" + NUM.getAndIncrement());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    if (isAcquired) {
                        semaphore.release();
                    }
                }
                },"t"+i).start();
        }
    }
}
